﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace SXICE.Core.Helpers
{
    /// <summary>
    /// 转换帮助类
    /// </summary>
    public class ConvertHelper
    {
        #region Json转换

        /// <summary>
        /// 对象转Json
        /// </summary>
        /// <typeparam name="T">要转换的对象泛型</typeparam>
        /// <param name="source">要转换的对象</param>
        /// <returns>转换后的字符串</returns>
        public static string ToJson<T>(T source)
        {
            if (null == source)
                return null;
            if (source is string str)
                return str;
            try
            {
                return JsonConvert.SerializeObject(source);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// Json转换为对象
        /// </summary>
        /// <typeparam name="T">要转换成的泛型</typeparam>
        /// <param name="json">Json数据</param>
        /// <returns>转换后的对象</returns>
        public static T JsonToObject<T>(string json)
        {
            try
            {
                if (typeof(T).Name == "String")
                {
                    return (T)(object)json;
                }
                return JsonConvert.DeserializeObject<T>(json);
            }
            catch
            {
                return default;
            }
        }

        /// <summary>
        /// Json转换为对象
        /// </summary>
        /// <param name="json">Json数据</param>
        /// <param name="type">要转换的类型</param>
        /// <returns>转换后的对象</returns>
        public static object JsonToObject(string json, Type type)
        {
            return JsonConvert.DeserializeObject(json, type);
        }

        #endregion
    }
}
